package com.glink.manage.common;

import com.glink.common.contants.ErrorCode;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.X509Certificate;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/6/24 15:49
 */
@Slf4j
public class CommonUtils {

    /**
     * 获取当前登录用户的userId
     *
     * @return 用户ID
     * @throws GeneralSimpleException
     */
    public static String extractUserIdtByToken() throws GeneralSimpleException {
        String userId = BaseCommonUtils.extractUserIdtByToken();
        if(StringUtils.isBlank(userId)){
            throw new GeneralSimpleException("100001");
        }
        return userId;
    }

    /**
     * 智能设备sip用户名
     */
    public static String getSipCode(){
        return RandomStringUtils.random(10, false, true) + "118" + RandomStringUtils.random(6, false, true) + "0";
    }

    /**
     * post请求
     */
    public static String sendPost(String url, String json) throws GeneralSimpleException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
                // 创建一个信任所有证书的TrustManager
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public void checkServerTrusted(X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public X509Certificate[] getAcceptedIssuers() {
                                return new X509Certificate[]{};
                            }
                        }
                };

                // 创建一个SSLContext，信任所有证书
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // 创建HttpClient实例，使用自定义的SSLContext和主机名验证器
                httpClient = HttpClients.custom()
                        .setSSLContext(sslContext)
                        .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .build();

            //httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            //设置请求状态参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setSocketTimeout(10000)
                    .setConnectTimeout(10000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(json,"UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception e) {
            log.error("请求服务异常", e);
            throw new GeneralSimpleException(ErrorCode.API_REQUEST_FAILED.getValue(),ErrorCode.API_REQUEST_FAILED.getDesc());
        } finally {
            //释放资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * get请求
     */
    public static String sendGet(String url) throws GeneralSimpleException{
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        try {
            // 创建一个信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            // 创建一个SSLContext，信任所有证书
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // 创建HttpClient实例，使用自定义的SSLContext和主机名验证器
            httpClient = HttpClients.custom()
                    .setSSLContext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

            //httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            //设置请求状态参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setSocketTimeout(20000)
                    .setConnectTimeout(10000).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception e) {
            log.error("请求服务异常", e);
            throw new GeneralSimpleException(ErrorCode.API_REQUEST_FAILED.getValue(),ErrorCode.API_REQUEST_FAILED.getDesc());
        } finally {
            //释放资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
